package com.shuiyun.chat.utils;

import com.google.gson.Gson;
import com.shuiyun.chat.entity.bo.DeserializationBO;
import com.shuiyun.chat.entity.message.Message;
import com.shuiyun.chat.enums.SerializeType;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @author shuiyun
 * @program oicq
 * @description 反序列化工具
 * @create 2021-05-12 15:36
 **/
@Slf4j
public class DeserializationUtil {

    private final Map<Integer, Function<DeserializationBO, Message>> functionMap = new HashMap<>();

    public DeserializationUtil(){
        functionMap.put(SerializeType.jdk.getType(),this::jdk);
        functionMap.put(SerializeType.json.getType(),this::json);
    }

    public Message invoke(Integer type, DeserializationBO bo){
        Function<DeserializationBO, Message> function = functionMap.get(type);
        if (null == function){
            throw new RuntimeException("当前类型不存在:"+type);
        }
        return function.apply(bo);
    }

    private Message json(DeserializationBO bo) {
        try {
            Gson gson = new Gson();
            String json = new String(bo.getBytes(), StandardCharsets.UTF_8);
            return gson.fromJson(json, bo.getMessage().getClass());
        }catch (Exception e){
            log.error("反序列化失败",e);
        }
        return null;
    }

    private Message jdk(DeserializationBO bo)  {
        try {
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bo.getBytes()));
            Object o = ois.readObject();
            Gson gson = new Gson();
            return gson.fromJson(gson.toJson(o),bo.getMessage().getClass());
        }catch (Exception e){
         log.error("反序列化失败",e);
        }
        return null;
    }


}
